﻿using Autofac;
using NLog;
using Quartz;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace MT.Job.Core
{
    public class SampleSchedule
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 注册窗口
        /// </summary>
        private readonly IContainer _container;

        public SampleSchedule(IContainer container)
        {
            _container = container;
        }

        public async Task Start()
        {
            Console.WriteLine("MT.Job.Task Started!");
            _logger.Info("MT.Job.Task Started!");

            await AddMyJob1Async();
        }

        public async Task AddMyJob1Async()
        {
            var appointmentExpiredHandleTrigger = TriggerBuilder.Create().WithDailyTimeIntervalSchedule(x => x.OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(00, 00))
                    .WithIntervalInHours(24))
                .Build();

            var scheduler = _container.Resolve<IScheduler>();
            var appointmentExpiredHandleJob = JobBuilder.Create<MyJob1>().Build();
   
            var appointmentExpiredHandleJobCts = new CancellationTokenSource();

            await scheduler.ScheduleJob(appointmentExpiredHandleJob, appointmentExpiredHandleTrigger, appointmentExpiredHandleJobCts.Token).ConfigureAwait(true);
            await scheduler.Start(appointmentExpiredHandleJobCts.Token).ConfigureAwait(true);
            appointmentExpiredHandleJobCts.Cancel();

            var medicalRegisterExpiredHandleJob = JobBuilder.Create<MyJob1>().Build();
         
            var medicalRegisterExpiredHandleTrigger = TriggerBuilder.Create().WithDailyTimeIntervalSchedule(x => x.OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(00, 00))
                    .WithIntervalInHours(24))
                .Build();

            var medicalRegisterExpiredHandleCts = new CancellationTokenSource();

            await scheduler.ScheduleJob(medicalRegisterExpiredHandleJob, medicalRegisterExpiredHandleTrigger, medicalRegisterExpiredHandleCts.Token).ConfigureAwait(true);
            await scheduler.Start(medicalRegisterExpiredHandleCts.Token).ConfigureAwait(true);
            medicalRegisterExpiredHandleCts.Cancel();



            Console.WriteLine("======================");
            Console.WriteLine("Press Enter to exit...");
            Console.WriteLine("======================");
            // await scheduler.Shutdown().ConfigureAwait(true);//关闭
        }

        public void Stop()
        {
            Console.WriteLine("MT.Job.Task Stoped!");
            _logger.Info("MT.Job.Task Stoped!");
        }
    }
}
